package com.seu.project.seuquiz.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.project.seuquiz.annotation.AuthCheck;
import com.seu.project.seuquiz.common.BaseResponse;
import com.seu.project.seuquiz.common.DeleteRequest;
import com.seu.project.seuquiz.common.ErrorCode;
import com.seu.project.seuquiz.common.ResultUtils;
import com.seu.project.seuquiz.exception.BusinessException;
import com.seu.project.seuquiz.model.converter.QuestionConverter;
import com.seu.project.seuquiz.model.dto.question.QuestionAddRequest;
import com.seu.project.seuquiz.model.dto.question.QuestionQueryByIdsRequest;
import com.seu.project.seuquiz.model.dto.question.QuestionQueryRequest;
import com.seu.project.seuquiz.model.dto.question.QuestionUpdateRequest;
import com.seu.project.seuquiz.model.entity.Question;
import com.seu.project.seuquiz.model.vo.QuestionVO;
import com.seu.project.seuquiz.service.QuestionService;
import com.seu.project.seuquiz.util.EasyExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题库接口
 * @author SoftPro
 * @createDate: 2023-07-16 09:47
 */
@RestController
@RequestMapping("/question")
@Api(tags = "题目接口")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    //region_start: 基本增删改查

    /**
     * 新增题目
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("addQuestion：新增题目")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String content = request.getContent();
        String selection = QuestionConverter.selectionInternalToSelection(request.getSelection());
        String answer = request.getAnswer();
        String analysis = request.getAnalysis();
        String remark = request.getRemark();
        Integer score = request.getScore();
        String questionType = request.getQuestionType();
        String type = request.getType();
        Integer difficulty = request.getDifficulty();
        Integer status = request.getStatus();

        long id = questionService.questionAdd(content, selection, answer, score, analysis, remark, questionType, type, difficulty, status);
        return ResultUtils.success(id);
    }

    /**
     * 删除题目
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("deleteQuestionById：根据id删除题目")
    public BaseResponse<Boolean> deleteQuestionById(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = questionService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 批量删除
     * @param deleteRequest
     * @return
     */
    @PostMapping("/deleteByIds")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("deleteQuestionByIds：根据ids删除题目列表")
    public BaseResponse<Boolean> deleteQuestionByIds(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getIds().size() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = questionService.removeByIds(deleteRequest.getIds());
        return ResultUtils.success(b);
    }

    /**
     * 更新题目
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("updateQuestion：更新题目")
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest updateRequest){
        if(updateRequest==null || updateRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = questionService.updateById(QuestionConverter.questionUpdateRequestToQuestion(updateRequest));
        return ResultUtils.success(b);
    }

    /**
     * 根据id查询题目
     * @param id
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("getQuestionById：根据id查询题目")
    public BaseResponse<QuestionVO> getQuestionById(int id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        return ResultUtils.success(QuestionConverter.toQuestionVO(question));
    }

    /**
     * 根据ids查询题目
     * @param request
     * @return
     */
    @PostMapping("/getByIds")
    @ApiOperation("getQuestionByIds：根据ids查询题目")
    public BaseResponse<Page<QuestionVO>> getQuestionByIds(@RequestBody QuestionQueryByIdsRequest request){
        Long[] ID = request.getIds();
        long current = request.getCurrent();
        long pageSize = request.getPageSize();
        List<Long> ids = Arrays.asList(ID);
        if(ids == null && ids.size() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<Question> questions = questionService.listByIds(ids);
        Page<QuestionVO> questionVOPage = new Page<>(current, pageSize);
        questionVOPage.setRecords(questions.stream().map(QuestionConverter::toQuestionVO).sorted((o1, o2) -> {return o2.getCreateTime().compareTo(o1.getCreateTime());}).collect(Collectors.toList()));
        questionVOPage.setTotal(questions.size());
        return ResultUtils.success(questionVOPage);
    }

    /**
     * 根据查询条件获取全部的题目信息
     * @param request
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("listQuestion：获取全部题目")
    public BaseResponse<List<QuestionVO>> listQuestion(QuestionQueryRequest request) {
        QueryWrapper<Question> queryWrapper = questionService.getQueryWrapper(request);
        List<Question> list = questionService.list(queryWrapper);
        List<QuestionVO> questionVOList = list.stream().map(it -> QuestionConverter.toQuestionVO(it)).collect(Collectors.toList());
        return ResultUtils.success(questionVOList);
    }

    /**
     * 分页获取题目
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @ApiOperation("listQuestionByPage：分页获取全部题目")
    public BaseResponse<Page<QuestionVO>> listQuestionByPage(QuestionQueryRequest request) {
        System.out.println(request);
        long current = 1;
        long size = 10;
        if (request != null) {
            current = request.getCurrent();
            size = request.getPageSize();
        }
        QueryWrapper<Question> queryWrapper = questionService.getQueryWrapper(request);
        Page<Question> page = questionService.page(new Page(current, size), queryWrapper);
        return ResultUtils.success(QuestionConverter.questionPageToQuestionVOPage(page));
    }

    // region_end

    /**
     * 以 excel 方式批量添加题目
     * @param multipartFile
     * @return
     */
    @PostMapping("/add/batch")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("listQuestion：批量添加题目")
    public BaseResponse<String> addQuestionBatch(@RequestPart("file") MultipartFile multipartFile){
        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        if (size > ONE_MB) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件超过 1M");
        }
        // 校验文件后缀   aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!validFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件后缀非法");
        }

        List<Question> questions = EasyExcelUtils.excelToQuestionList(multipartFile);
        boolean saveBatch = questionService.saveBatch(questions);
        if (!saveBatch) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success("题目添加完成");
    }

    // todo: 返回一个添加示例的excel文件
}

